using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Impact.Infrastructure;
using System.IO;
using System.Collections.Generic;

namespace Impact.Web.Admin.Controls
{
    /// <summary>
    /// code-behind for the folder picker control
    /// </summary>
    public partial class FolderPicker : UserControl
    {

        /// <summary>
        /// perform extra processing when loading the control
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!IsPostBack)
            {
                string path = Server.MapPath(BasePath);
                AddFolder(new DirectoryInfo(path), path);
                folderPicker.SelectedValue = initSelectedValue;
            }

        }

        private void AddFolder(DirectoryInfo folder, string rootPath)
        {
            List<DirectoryInfo> directories = new List<DirectoryInfo>();
            directories.AddRange(folder.GetDirectories("*", SearchOption.AllDirectories));

            foreach (DirectoryInfo directory in directories)
            {
                List<FileInfo> files = new List<FileInfo>();
                files.AddRange(directory.GetFiles("*.jpg"));
                files.AddRange(directory.GetFiles("*.png"));
                files.AddRange(directory.GetFiles("*.gif"));

                if (files.Count > 0)
                {
                    string shortPath = directory.FullName.Replace(rootPath, string.Empty);
                    folderPicker.Items.Add(shortPath);
                }
            }
        }

        /// <summary>
        /// event handler to validate that the control is valid
        /// </summary>
        protected void ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = folderPicker.SelectedIndex > 0;
        }


        /// <summary>
        /// gets or sets the root folder to start the folder treeview from
        /// </summary>
        public string BasePath
        {
            get { return initBasePath; }
            set { initBasePath = value; }
        }
        private string initBasePath;

        /// <summary>
        /// gets or sets the path for the selected folder
        /// </summary>
        public string SelectedFolderPath
        {
            get { return folderPicker.SelectedValue; }
            set { initSelectedValue = value; }
        }
        private string initSelectedValue;

 

    }
}